import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { NextRequest } from 'next/server';
import { v4 as uuidv4 } from 'uuid';

// 检查敏感词函数
async function checkIllegalWords(content: string): Promise<{ isIllegal: boolean; illegalWords: string[] }> {
  try {
    // 获取所有启用的敏感词
    const illegalWords = await prisma.illegalWords.findMany({
      where: { isEnable: 1 }
    });

    const foundIllegalWords: string[] = [];

    // 检查内容中是否包含敏感词
    illegalWords.forEach(word => {
      if (word.words && content.includes(word.words)) {
        foundIllegalWords.push(word.words);
      }
    });

    return {
      isIllegal: foundIllegalWords.length > 0,
      illegalWords: foundIllegalWords
    };
  } catch (error) {
    console.error('检查敏感词失败:', error);
    return { isIllegal: false, illegalWords: [] };
  }
}

// 获取帖子列表
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const id = searchParams.get('id');
    
    // 如果提供了ID，则获取单个帖子
    if (id) {
      const post = await prisma.post.findUnique({
        where: { id },
        include: {
          user: true,
          category: true,
          postCount: true
        }
      });
      
      if (!post) {
        return NextResponse.json(
          { error: '帖子不存在' },
          { status: 404 }
        );
      }
      
      return NextResponse.json({ post }, { status: 200 });
    }
    
    // 获取所有帖子
    const posts = await prisma.post.findMany({
      include: {
        user: {
          select: {
            openId: true,
            uName: true,
            avatarUrl: true
          }
        },
        category: true,
        postCount: {
          select: {
            viewCount: true,
            likeCount: true,
            shareCount: true,
            commentCount: true
          }
        }
      },
      orderBy: {
        createTime: 'desc'
      }
    });
    
    return NextResponse.json({ posts }, { status: 200 });
  } catch (error) {
    console.error('获取帖子数据失败:', error);
    return NextResponse.json(
      { error: '获取帖子数据失败' },
      { status: 500 }
    );
  }
}

// 创建帖子
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { uId, images, content, categoryId, status = 1 } = body;
    
    // 验证必要字段
    if (!uId) {
      return NextResponse.json(
        { error: '用户ID不能为空' },
        { status: 400 }
      );
    }
    
    if (!content) {
      return NextResponse.json(
        { error: '帖子内容不能为空' },
        { status: 400 }
      );
    }
    
    // 检查敏感词
    const illegalWordsCheck = await checkIllegalWords(content);
    if (illegalWordsCheck.isIllegal) {
      return NextResponse.json(
        { 
          error: '帖子内容包含敏感词',
          illegalWords: illegalWordsCheck.illegalWords 
        },
        { status: 400 }
      );
    }
    
    // 生成唯一ID
    const id = uuidv4().replace(/-/g, '').substring(0, 30);
    const now = new Date();
    
    // 创建帖子
    const post = await prisma.post.create({
      data: {
        uId,
        images,
        content,
        categoryId: categoryId ? parseInt(categoryId.toString()) : null,
        createTime: now,
        updateTime: now,
        status,
        user: {
          connect: {
            openId: uId
          }
        },
        postCount: {
          create: {
            viewCount: 0,
            likeCount: 0,
            shareCount: 0,
            commentCount: 0
          }
        }
      },
      include: {
        postCount: true
      }
    });
    
    return NextResponse.json({ post }, { status: 201 });
  } catch (error) {
    console.error('创建帖子失败:', error);
    return NextResponse.json(
      { error: '创建帖子失败' },
      { status: 500 }
    );
  }
}

// 更新帖子
export async function PUT(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '帖子ID不能为空' },
        { status: 400 }
      );
    }
    
    const body = await request.json();
    const { images, content, categoryId, status } = body;
    
    // 检查帖子是否存在
    const existingPost = await prisma.post.findUnique({
      where: { id }
    });
    
    if (!existingPost) {
      return NextResponse.json(
        { error: '帖子不存在' },
        { status: 404 }
      );
    }
    
    // 如果更新内容，检查敏感词
    if (content) {
      const illegalWordsCheck = await checkIllegalWords(content);
      if (illegalWordsCheck.isIllegal) {
        return NextResponse.json(
          { 
            error: '帖子内容包含敏感词',
            illegalWords: illegalWordsCheck.illegalWords 
          },
          { status: 400 }
        );
      }
    }
    
    // 更新帖子
    const updatedPost = await prisma.post.update({
      where: { id },
      data: {
        images: images !== undefined ? images : undefined,
        content: content !== undefined ? content : undefined,
        categoryId: categoryId !== undefined ? (categoryId ? parseInt(categoryId.toString()) : null) : undefined,
        status: status !== undefined ? status : undefined,
        updateTime: new Date()
      },
      include: {
        user: true,
        category: true,
        postCount: true
      }
    });
    
    return NextResponse.json({ post: updatedPost }, { status: 200 });
  } catch (error) {
    console.error('更新帖子失败:', error);
    return NextResponse.json(
      { error: '更新帖子失败' },
      { status: 500 }
    );
  }
}

// 删除帖子
export async function DELETE(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { error: '帖子ID不能为空' },
        { status: 400 }
      );
    }
    
    // 检查帖子是否存在
    const existingPost = await prisma.post.findUnique({
      where: { id }
    });
    
    if (!existingPost) {
      return NextResponse.json(
        { error: '帖子不存在' },
        { status: 404 }
      );
    }
    
    // 删除帖子计数
    await prisma.postCount.delete({
      where: { countId: id }
    });
    
    // 删除帖子
    await prisma.post.delete({
      where: { id }
    });
    
    return NextResponse.json(
      { message: '帖子删除成功' },
      { status: 200 }
    );
  } catch (error) {
    console.error('删除帖子失败:', error);
    return NextResponse.json(
      { error: '删除帖子失败' },
      { status: 500 }
    );
  }
}